<?php
namespace app\scodetrace\controller;

use \app\scodetrace\encoder\PcodeEncoder;
use \app\scodetrace\encoder\TcodeEncoder;

class Pcodes extends \app\common\controller\Base {
	protected $modelname='Pcode';

	protected function _index(){
		$condition=[];
		$param=$this->param;

		return $condition;
	}

  public function create() {
    $pcodeModel = model($this->modelname);
    $codes = $this->param('codes');
    $force = $this->param('force',false);
    $isScode = true;
    if (count($codes)) {
      $error = [];
      $prefix = substr($codes[0], 0, 3);
      if ($prefix == 'SYC') {
        $ids = TcodeEncoder::getInstance()->decode($codes);
        foreach ($ids as $k => $v) {
          if (!$v)
            $error[] = $codes[$k];
        }
        if (count($error)) {
          return json_pack(['ids' => $error,'errmsg' => '无法识别的溯源码(请不要混用装箱码)']);
        }
      } else if ($prefix == 'PKC') {
        $ids = PcodeEncoder::getInstance()->decode($codes);
        foreach ($ids as $k => $v) {
          if (!$v)
            $error[] = $codes[$k];
        }
        if (count($error)) {
          return json_pack(['ids' => $error,'errmsg' => '无法识别的装箱码(请不要混用溯源码)']);
        }
        $isScode = false;
      } else {
        return json_pack(['ids'=>$codes,'errmsg'=> '存在无法识别的码类型']);
      }
    } else {
      return json_pack(['ids'=>[],'errmsg'=> '请指定溯源码或装箱码']);
    }

    $result = $pcodeModel->createPcode($ids,$isScode,$force);
    if ($result === false) {
      return json_pack($pcodeModel->getError());
    } else {
      return json_pack($result);
    }
  }
}

?>